<div x-data="alpineSources()" x-init="getSources()" id="sourcePage">
    <div>
        <h2>Fact Sources</h2>
        <p>
            Facts are identifiable pieces of data, collected by agents or loaded when the server starts.
            A source is a collection of facts. Rules are boundaries to ensure specific traits cannot be used.
        </p>
    </div>
    <hr>
    <div>
        <!-- TOP PANEL -->
        <div>
            <div class="is-flex is-flex-direction-row" x-data="{filterKeyword: ''}">
                <!-- SEARCH BAR -->
                <div class="mb-4 is-flex is-justify-content-space-between is-flex-direction-column">
                    <div class="is-flex is-align-items-center filter-search-box">
                        <i class="fas fa-search"></i>
                        <input class="input is-small"
                               id="source-search"
                               placeholder="Fact source"
                               x-model="filterKeyword"
                               x-on:keyup="filterSources($el.value)">
                        <i class="fas fa-times"
                           x-on:click="filterSources(''); filterKeyword=''"></i>
                    </div>
                    <label class="is-size-7" for="source-search">
                        <em x-text="filterKeyword !== '' ? ('searching: ' + filterKeyword) : 'type fact source name'"></em>
                    </label>
                </div>
                <div class="pl-0 is-flex is-align-content-flex-start">
                    <button
                            type="button"
                            class="ml-2 button is-primary is-small"
                            x-on:click="addSource(filterKeyword)"
                            title="Create a new source">
                        <i class="pr-1 fas fa-plus"></i>
                        <span>Add Source</span>
                    </button>
                    <button type="button"
                            x-bind:disabled="!selectedSource"
                            class="ml-2 button is-primary is-small"
                            x-on:click="duplicateSource(selectedSource)"
                            title="Duplicate selected source">
                        <i class="pr-1 fas fa-plus"></i>
                        <span>Duplicate</span>
                    </button>
                    <button type="button"
                            x-bind:disabled="!selectedSource"
                            class="ml-2 button is-primary is-small"
                            x-on:click="openModalData.name = 'deleteSource'; openModalData.item = selectedSource"
                            title="Delete selected source">
                        <i class="pr-1 fas fa-trash"></i>
                    </button>
                </div>
            </div>

            <!-- SOURCES MENU -->
            <div class="is-flex is-flex-direction-row is-justify-content-flex-start sources-menu-container">
                <template x-if="filteredSources.length < 1">
                    <em class="is-flex is-justify-content-center">No sources available; click on the 'Add Source'
                        button to get started.</em>
                </template>
                <template x-for="source of filteredSources" :key="source.id" x-data="{ editSourceName: false}">
                    <button class="pt-2 no-style source-menu-links"
                            x-bind:class="selectedSource === source ? 'active' : ''"
                            x-on:click="handleSelectSource(source)">
                        <i class="fas fa-project-diagram"></i>
                        <span x-on:click="editSourceName = (selectedSource === source)"
                              x-show="!editSourceName || selectedSource !== source" x-text="source.name"></span>
                        <label for="edit-source-name" x-show="false">Edit source name</label>
                        <textarea id="edit-source-name"
                                  @click.outside="handleEditSource(editSourceName)"
                                  class="is-small edit-field"
                                  x-model="source.name"
                                  x-show="editSourceName && selectedSource === source"
                                  contenteditable
                                  spellcheck="false"></textarea>
                    </button>
                </template>
            </div>
        </div>

        <!-- CONTENT -->
        <template x-if="!selectedSource">
            <em class="is-flex is-justify-content-center">Click on a fact source to get started.</em>
        </template>

        <template x-if="selectedSource">
            <div>
                <!-- FACTS CONTENT -->
                <div class="my-5" x-data="{collapseFacts: false}">
                    <div class="collapsible-header">
                        <button class="button px-0 no-style is-size-4" x-on:click="collapseFacts = !collapseFacts"
                                x-bind:class="collapseFacts ? 'collapsed' : 'expanded'">
                            Facts
                        </button>
                    </div>
                    <span class="navbar-divider"></span>
                    <div x-show="!collapseFacts" x-data="{selectedFact: null}">
                        <!-- FACTS SEARCH BAR -->
                        <div class="is-flex is-flex-direction-row" x-data="{factsFilterKeyword: ''}">
                            <div class="mb-4 is-flex is-justify-content-space-between is-flex-direction-column">
                                <div class="is-flex is-align-items-center filter-search-box">
                                    <i class="fas fa-search"></i>
                                    <input class="input is-small"
                                           id="fact-search"
                                           placeholder="Fact keyword"
                                           x-model="factsFilterKeyword"
                                           x-on:keyup="filterFacts($el.value)">
                                    <i class="fas fa-times"
                                       x-on:click="filterFacts(''); factsFilterKeyword=''"></i>
                                </div>
                                <label class="is-size-7" for="fact-search">
                                    <em x-text="factsFilterKeyword !== '' ? ('searching: ' + factsFilterKeyword) : 'type fact trait or value'"></em>
                                </label>
                            </div>
                            <div class="pl-0 is-flex is-align-content-flex-start">
                                <button type="button"
                                        class="ml-2 button is-primary is-small"
                                        x-on:click="showAddFactRow = true; selectedFact = null">
                                    <span class="icon"><i class="fas fa-plus"></i></span>
                                    <span>Add Fact</span>
                                </button>
                                <button type="button"
                                        x-bind:disabled="!selectedFact"
                                        class="ml-2 button is-primary is-small"
                                        x-on:click="openModalData.name = 'deleteFact'; openModalData.item = selectedFact"
                                        title="Delete selected fact">
                                    <i class="pr-1 fas fa-trash"></i>
                                </button>

                            </div>
                        </div>

                        <!-- FACTS TABLE -->
                        <table class="table is-striped">
                            <thead>
                            <tr class="table-header">
                                <th></th>
                                <th>Origin</th>
                                <th>Fact Trait</th>
                                <th>Value</th>
                                <th>Score</th>
                                <th></th>
                            </tr>
                            </thead>
                            <template x-if="filteredFacts.length < 1 && !showAddFactRow">
                                <tbody>
                                <tr>
                                    <td colspan="6" class="text-align-center py-2">
                                        <em>No facts; click 'Add Fact' to get started.</em>
                                    </td>
                                </tr>
                                </tbody>
                            </template>
                            <tbody>
                            <template x-if="showAddFactRow">
                                <tr x-data="{newFact: EMPTY_FACT_OBJECT}">
                                    <td></td>
                                    <td></td>
                                    <td @click.outside="selectedFact = {}">
                                        <label x-show="false" for="new-fact-trait">Fact Trait</label>
                                        <input id="new-fact-trait" class="input is-small" x-model="newFact.trait" contenteditable>
                                    </td>
                                    <td>
                                        <label x-show="false" for="new-fact-value">Fact Value</label>
                                        <input id="new-fact-value" class="input is-small" x-model="newFact.value" contenteditable>
                                    </td>
                                    <td>
                                        <label x-show="false" for="new-fact-score">Fact Score</label>
                                        <input class="is-small input fact-score" id="new-fact-score" type="number" x-model="newFact.score" min="0"/>
                                    </td>
                                    <td>
                                        <button type="button"
                                                class="button is-small is-primary"
                                                x-on:click="addFact(newFact); newFact = EMPTY_FACT_OBJECT">
                                            Add
                                        </button>
                                    </td>
                                </tr>
                            </template>
                            <template x-for="(fact, index) in filteredFacts" :key="fact.unique">
                                <tr x-on:click="selectedFact = fact; showAddFactRow = false;"
                                    x-bind:class="selectedFact === fact ? 'selected' : ''">
                                    <td class="index-column" x-text="index"></td>
                                    <td x-bind:class="(fact.origin_type) ? 'is-size-6 origin-' + fact.origin_type : ''"
                                        x-text="fact.origin_type"></td>
                                    <td x-show="selectedFact !== fact" x-text="fact.trait"></td>
                                    <td x-show="selectedFact === fact">
                                        <label x-show="false" for="edit-fact-trait">Fact Trait</label>
                                        <input id="edit-fact-trait" class="input is-small" x-model="fact.trait" contenteditable>
                                    </td>
                                    <td x-show="selectedFact !== fact" x-text="fact.value"></td>
                                    <td x-show="selectedFact === fact">
                                        <label x-show="false" for="edit-fact-value">Fact Value</label>
                                        <input id="edit-fact-value" class="input is-small" x-model="fact.value" contenteditable>
                                    </td>
                                    <td x-text="fact.score"></td>
                                    <td>
                                        <button x-show="selectedFact === fact"
                                                type="button"
                                                class="button is-small is-primary"
                                                x-on:click="updateFactSource()">
                                            Save
                                        </button>
                                    </td>
                                </tr>
                            </template>
                            </tbody>
                        </table>
                    </div>
                </div>
                <!-- RULES CONTENT -->
                <div class="my-5" x-data="{collapseRules: false}">
                    <div class="collapsible-header">
                        <button class="button px-0 no-style is-size-4" x-on:click="collapseRules = !collapseRules"
                                x-bind:class="collapseRules ? 'collapsed' : 'expanded'">
                            Rules
                        </button>
                    </div>
                    <span class="navbar-divider"></span>
                    <div x-show="!collapseRules" x-data="{selectedRule: null}">
                        <!-- RULES SEARCH BAR -->
                        <div class="is-flex is-flex-direction-row" x-data="{rulesFilterKeyword: ''}">
                            <div class="mb-4 is-flex is-justify-content-space-between is-flex-direction-column">
                                <div class="is-flex is-align-items-center filter-search-box">
                                    <i class="fas fa-search"></i>
                                    <input class="input is-small"
                                           id="rule-search"
                                           placeholder="Rule keyword"
                                           x-model="rulesFilterKeyword"
                                           x-on:keyup="filterRules($el.value)">
                                    <i class="fas fa-times"
                                       x-on:click="filterRules(''); rulesFilterKeyword=''"></i>
                                </div>
                                <label class="is-size-7" for="rule-search">
                                    <em x-text="rulesFilterKeyword !== '' ? ('searching: ' + rulesFilterKeyword) : 'type match rule or fact trait'"></em>
                                </label>
                            </div>
                            <div class="pl-0 is-flex is-align-content-flex-start">
                                <button type="button"
                                        class="ml-2 button is-primary is-small"
                                        x-on:click="showAddRuleRow = true; selectedRule = null">
                                    <span class="icon"><i class="fas fa-plus"></i></span>
                                    <span>Add Rule</span>
                                </button>
                                <button type="button"
                                        x-bind:disabled="!selectedRule"
                                        class="ml-2 button is-primary is-small"
                                        x-on:click="openModalData.name = 'deleteRule'; openModalData.item = selectedRule"
                                        title="Delete selected rule">
                                    <i class="pr-1 fas fa-trash"></i>
                                </button>

                            </div>
                        </div>

                        <!-- RULES TABLE -->
                        <table class="table is-striped">
                            <thead>
                            <tr>
                                <th class="index-column">Order</th>
                                <th>Match</th>
                                <th>Fact Trait</th>
                                <th class="text-align-center">Action</th>
                                <th></th>
                            </tr>
                            </thead>
                            <template x-if="filteredRules.length < 1 && !showAddRuleRow">
                                <tbody>
                                <tr>
                                    <td colspan="5" class="text-align-center py-2">
                                        <em>No rules; click 'Add Rule' to get started.</em>
                                    </td>
                                </tr>
                                </tbody>
                            </template>
                            <tbody>
                            <template x-if="showAddRuleRow">
                                <tr x-data="{newRule: EMPTY_RULE_OBJECT}">
                                    <td></td>
                                    <td>
                                        <label x-show="false" for="new-rule-match">Rule Match</label>
                                        <input id="new-rule-match" class="input is-small" x-model="newRule.match" contenteditable>
                                    </td>
                                    <td>
                                        <label x-show="false" for="new-rule-trait">Rule Trait</label>
                                        <input id="new-rule-trait" class="input is-small" x-model="newRule.trait" contenteditable>
                                    </td>
                                    <td>
                                        <label x-show="false" for="new-rule-action">Rule Action</label>
                                        <div class="toggleContainer is-flex is-justify-content-center"
                                             id="new-rule-action">
                                            <label class="has-text-danger" for="toggleAction">DENY</label>
                                            <div class="toggleSwitch mx-2">
                                                <input type="checkbox"
                                                       id="toggleAction"
                                                       x-model="newRule.action"
                                                       x-bind:checked="newRule.action === 'ALLOW' ? 'checked' : null"/>
                                                <span class="toggleSlider toggleSliderRound"
                                                      x-on:click="newRule.action = (newRule.action === 'ALLOW' ? 'DENY' : 'ALLOW')"
                                                      x-bind:class="newRule.action === 'ALLOW' ? 'toggle-on' : 'toggle-off'">
                                                    <span x-bind:class="newRule.action === 'ALLOW' ? 'toggle-slider-on' : 'toggle-slider-off'"></span>
                                                </span>
                                            </div>
                                            <label class="has-text-success" for="toggleAction">ALLOW</label>
                                        </div>
                                    </td>
                                    <td>
                                        <button type="button"
                                                class="button is-small is-primary"
                                                x-on:click="addRule(newRule); newRule = EMPTY_RULE_OBJECT">
                                            Add
                                        </button>
                                    </td>
                                </tr>
                            </template>
                            <template x-for="(rule, index) in filteredRules">
                                <tr x-on:click="selectedRule = rule; showAddRuleRow = false;"
                                    x-bind:class="selectedRule === rule ? 'selected' : ''">
                                    <td class="index-column" x-text="index"></td>
                                    <td x-show="selectedRule === rule">
                                        <label x-show="false" for="edit-rule-match">Rule Match</label>
                                        <input id="edit-rule-match" class="input is-small" x-model="rule.match" contenteditable>
                                    </td>
                                    <td x-show="selectedRule !== rule" x-text="rule.match"></td>
                                    <td x-show="selectedRule === rule">
                                        <label x-show="false" for="edit-rule-trait">Rule Trait</label>
                                        <input id="edit-rule-trait" class="input is-small" x-model="rule.trait" contenteditable>
                                    </td>
                                    <td x-show="selectedRule !== rule" x-text="rule.trait"></td>
                                    <td x-show="selectedRule === rule">
                                        <div class="toggleContainer is-flex is-justify-content-center">
                                            <label class="has-text-danger" for="toggleRuleAction">DENY</label>
                                            <div class="toggleSwitch mx-2">
                                                <input type="checkbox"
                                                       id="toggleRuleAction"
                                                       x-model="rule.action"
                                                       x-bind:checked="rule.action === 'ALLOW' ? 'checked' : null"/>
                                                <span class="toggleSlider toggleSliderRound"
                                                      x-on:click="rule.action = (rule.action === 'ALLOW' ? 'DENY' : 'ALLOW')"
                                                      x-bind:class="rule.action === 'ALLOW' ? 'toggle-on' : 'toggle-off'">
                                                    <span x-bind:class="rule.action === 'ALLOW' ? 'toggle-slider-on' : 'toggle-slider-off'"></span>
                                                </span>
                                            </div>
                                            <label class="has-text-success" for="toggleAction">ALLOW</label>
                                        </div>
                                    </td>
                                    <td x-show="selectedRule !== rule" class="text-align-center"
                                        x-bind:class="rule.action === 'ALLOW' ? 'has-text-success' : 'has-text-danger'"
                                        x-text="rule.action"></td>
                                    <td>
                                        <button x-show="selectedRule === rule" type="button"
                                                class="button is-small is-primary"
                                                x-on:click="updateFactSource()">
                                            Save
                                        </button>
                                    </td>
                                </tr>
                            </template>
                            </tbody>
                        </table>
                    </div>
                </div>
                <!-- RELATIONSHIPS CONTENT -->
                <div class="my-5" x-data="{collapseRelationships: false}">
                    <div class="collapsible-header">
                        <button class="button px-0 no-style is-size-4"
                                x-on:click="collapseRelationships = !collapseRelationships"
                                x-bind:class="collapseRelationships ? 'collapsed' : 'expanded'">
                            Relationships
                        </button>
                    </div>
                    <span class="navbar-divider"></span>
                    <div x-show="!collapseRelationships" x-data="{selectedRelationship: null}">
                        <!-- RELATIONSHIPS CONTROLS BAR -->
                        <div class="is-flex is-flex-direction-row">
                            <div class="pl-0 is-flex is-align-content-flex-start">
                                <button type="button"
                                        class="ml-2 button is-primary is-small"
                                        x-on:click="showAddRelationshipRow = true; selectedRelationship = null">
                                    <span class="icon"><i class="fas fa-plus"></i></span>
                                    <span>Add Relationship</span>
                                </button>
                                <button type="button"
                                        x-bind:disabled="!selectedRelationship"
                                        class="ml-2 button is-primary is-small"
                                        x-on:click="openModalData.name = 'deleteRelationship'; openModalData.item = selectedRelationship"
                                        title="Delete selected relationship">
                                    <i class="pr-1 fas fa-trash"></i>
                                </button>
                            </div>
                        </div>

                        <!-- RELATIONSHIPS TABLE -->
                        <table class="table is-striped">
                            <thead>
                                <tr>
                                    <th class="index-column"></th>
                                    <th>Source</th>
                                    <th>Edge</th>
                                    <th>Target</th>
                                    <th></th>
                                </tr>
                            </thead>
                            <template x-if="selectedSource.relationships.length < 1 && !showAddRelationshipRow">
                                <tbody>
                                    <tr>
                                        <td colspan="5" class="text-align-center py-2">
                                            <em>No relationships; click 'Add Relationship' to get started.</em>
                                        </td>
                                    </tr>
                                </tbody>
                            </template>
                            <tbody>
                                <template x-if="showAddRelationshipRow">
                                    <tr>
                                        <td></td>
                                        <td>
                                            <label x-show="false" for="new-relationship-source">Relationship Source</label>
                                            <input id="new-relationship-source" class="input is-small" x-model="newRelationship.sourceTrait" contenteditable>
                                        </td>
                                        <td>
                                            <label x-show="false" for="new-relationship-edge">Relationship Edge</label>
                                            <input id="new-relationship-edge" class="input is-small" x-model="newRelationship.edge" contenteditable>
                                        </td>
                                        <td>
                                            <label x-show="false" for="new-relationship-target">Relationship Target</label>
                                            <input id="new-relationship-target" class="input is-small" x-model="newRelationship.targetTrait" contenteditable>
                                        </td>
                                        <td>
                                            <button type="button"
                                                    class="button is-small is-primary"
                                                    x-on:click="addRelationship(newRelationship)">
                                                Add
                                            </button>
                                        </td>
                                    </tr>
                                </template>

                                <template x-for="(rel, index) in selectedSource.relationships">
                                    <tr x-on:click="selectedRelationship = rel; showAddRelationshipRow = false;" x-bind:class="selectedRelationship === rel ? 'selected' : ''">
                                        <td class="index-column" x-text="index"></td>
                                        <td x-text="rel.source?.trait"></td>
                                        <td x-text="rel.edge"></td>
                                        <td x-text="rel.target?.trait"></td>
                                        <td></td>
                                    </tr>
                                </template>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </template>
    </div>

    <!-- MODAL -->
    <template x-if="openModalData.item">
        <div class="modal is-active">
            <div class="modal-background"></div>
            <form class="m-1">
                <div class="modal-card">
                    <template x-if="openModalData.name.includes('delete')">
                        <div>
                            <header class="modal-card-head">
                                <p class="modal-card-title">Confirm Delete</p>
                            </header>
                            <section class="modal-card-body">
                                <div>
                                    <p>Are you sure you want to delete
                                        <em x-show="openModalData.name === 'deleteSource'" x-text="openModalData.item?.name"></em>
                                        <em x-show="openModalData.name === 'deleteFact'"
                                            x-text="openModalData.item?.name"></em>
                                        <em x-show="openModalData.name === 'deleteRule'"
                                            x-text="openModalData.item?.trait"></em>
                                        <em x-show="openModalData.name === 'deleteRelationship'"
                                            x-text="openModalData.item?.trait"></em>
                                        ?</p>
                                </div>
                            </section>
                        </div>
                    </template>
                    <footer class="modal-card-foot is-flex is-justify-content-space-between">
                        <button type="button" class="button ml-2 is-small"
                                x-on:click="resetModal()">
                            Cancel
                        </button>
                        <button x-show="openModalData.name === 'deleteSource'" type="button"
                                class="button is-primary is-small"
                                x-on:click="deleteSource(openModalData.item)">
                            Yes
                        </button>
                        <button x-show="openModalData.name === 'deleteFact'" type="button"
                                class="button is-primary is-small"
                                x-on:click="deleteFact(openModalData.item)">
                            Yes
                        </button>
                        <button x-show="openModalData.name === 'deleteRule'" type="button"
                                class="button is-primary is-small"
                                x-on:click="deleteRule(openModalData.item)">
                            Yes
                        </button>
                        <button x-show="openModalData.name === 'deleteRelationship'" type="button"
                                class="button is-primary is-small"
                                x-on:click="deleteRelationship(openModalData.item)">
                            Yes
                        </button>
                    </footer>
                </div>
            </form>
        </div>
    </template>
</div>

<script>
    function alpineSources() {
        return {
            // CONSTANTS
            EMPTY_FACT_OBJECT: { trait: '', value: '', score: 1 },
            EMPTY_RULE_OBJECT: { action: 'ALLOW', match: '', trait: '' },

            sources: [],
            filteredSources: [],
            filteredFacts: [],
            filteredRules: [],
            selectedSource: null,
            selectedRelationship: null,
            selectedFact: null,
            selectedRule: null,
            showAddFactRow: false,
            showAddRuleRow: false,
            showAddRelationshipRow: false,
            openModalData: { name: '', item: null },
            newRelationship: {
                sourceTrait: '',
                edge: '',
                targetTrait: ''
            },

            getSources() {
                apiV2('GET', '/api/v2/sources').then((sources) => {
                    this.sources = sources;
                    this.filteredSources = sources;
                }).catch((error) => {
                    toast('Error loading page', false);
                    console.error(error);
                });
            },

            handleSelectSource(source) {
                this.selectedSource = source;
                this.filteredFacts = source.facts;
                this.filteredRules = source.rules;
            },

            handleEditSource(editSourceName) {
                editSourceName = false;
                this.updateFactSource();
            },

            filterSources(input = '') {
                input = input.toLowerCase();
                this.filteredSources = this.sources.filter((s) => s.name.toLowerCase().includes(input));
            },

            filterFacts(input = '') {
                input = input.toLowerCase();
                this.filteredFacts = this.selectedSource.facts.filter((f) => (f.trait.toLowerCase().includes(input) || f.value.toLowerCase().includes(input)));
            },

            filterRules(input = '') {
                input = input.toLowerCase();
                this.filteredRules = this.selectedSource.rules.filter((r) => (r.match.toLowerCase().includes(input) || r.trait.toLowerCase().includes(input)));
            },

            addSource(newSourceName) {
                const newSource = {
                    name: newSourceName === '' ? 'new source' : newSourceName,
                    facts: [],
                    rules: [],
                    relationships: []
                };
                apiV2('POST', '/api/v2/sources', newSource).then((res) => {
                    toast('Added new fact source', res);
                    this.getSources();
                }).catch((error) => {
                    toast('Error adding source', false);
                    console.error(error);
                });
            },

            duplicateSource(source) {
                const newSource = { ...source, name: `${source.name} (copy)`, id: '' };
                apiV2('POST', '/api/v2/sources', newSource).then((res) => {
                    toast('Added new fact source', res);
                    this.getSources();
                }).catch((error) => {
                    toast('Error duplicating source', false);
                    console.error(error);
                });
            },

            addFact(newFact) {
                const updatedSource = { ...this.selectedSource };
                updatedSource.facts.push(newFact);
                apiV2('PUT', `/api/v2/sources/${this.selectedSource.id}`, updatedSource).then((res) => {
                    toast('Updated source', res);
                    this.showAddFactRow = false;
                }).catch((error) => {
                    toast('Error adding fact', false);
                    console.error(error);
                });
            },

            validateRule(newRule) {
                return !this.selectedSource.rules.find((r) => (r.match === newRule.match && r.trait === newRule.trait));
            },

            addRule(newRule) {
                if (!this.validateRule(newRule)) {
                    toast('Error: Rule already exists');
                    return;
                }
                const updatedSource = { ...this.selectedSource };
                updatedSource.rules.push(newRule);
                apiV2('PUT', `/api/v2/sources/${this.selectedSource.id}`, updatedSource).then((res) => {
                    toast('Updated source', true);
                    this.showAddRuleRow = false;
                }).catch((error) => {
                    toast('Error adding rule', false);
                    console.error(error);
                });
            },

            addRelationship() {
                const updatedSource = { ...this.selectedSource };
                updatedSource.relationships.push({
                    source: { trait: this.newRelationship.sourceTrait },
                    target: { trait: this.newRelationship.targetTrait },
                    edge: this.newRelationship.edge
                });
                apiV2('PUT', `/api/v2/sources/${this.selectedSource.id}`, updatedSource).then((res) => {
                    toast('Updated source', true);
                    this.showAddRelationshipRow = false;
                    this.newRelationship.sourceTrait = '';
                    this.newRelationship.targetTrait = '';
                    this.newRelationship.edge = '';
                }).catch((error) => {
                    toast('Error adding relationship', false);
                    console.error(error);
                });
            },

            deleteSource(source) {
                apiV2('DELETE', `/api/v2/sources/${source.id}`).then((res) => {
                    toast('Deleted fact source', true);
                    this.getSources();
                    this.resetModal();
                }).catch((error) => {
                    toast('Error deleting source', false);
                    console.error(error);
                });
            },

            deleteFact(fact) {
                this.selectedSource.facts.splice(this.selectedSource.facts.findIndex((f) => f.unique === fact.unique), 1);
                this.updateFactSource();
                this.resetModal();
            },

            deleteRule(rule) {
                this.selectedSource.rules.splice(this.selectedSource.rules.findIndex((r) => r === rule), 1);
                this.updateFactSource();
                this.resetModal();
            },

            deleteRelationship(rel) {
                this.selectedSource.relationships.splice(this.selectedSource.relationships.find((r) => r === rel), 1);
                this.updateFactSource();
                this.resetModal();
            },

            resetModal() {
                this.openModalData = { name: '', item: null };
            },

            updateFactSource() {
                apiV2('PATCH', `/api/v2/sources/${this.selectedSource.id}`, this.selectedSource).then((res) => {
                    toast('Updated source', true);
                    this.selectedFact = {};
                    this.selectedRule = {};
                    this.getSources();
                }).catch((error) => {
                    toast('Error loading page', false);
                    console.error(error);
                });
            },
        };
    }

    // # sourceURL=sources.js
</script>

<style>
    :scope {
        --primary-color: #8B0000;
        --dark-gray: gray;
        --light-gray: #e6e6e6;
        --decisions-color: #4fdcfc;
    }

    #sourcePage .edit-field {
        border-radius: 5px;
        width: 55px;
        height: 50px;
        padding: 5px;
    }

    #sourcePage .text-align-center {
        text-align: center !important;
    }

    #sourcePage button.no-style {
        background-color: transparent;
        border: none;
        box-shadow: none;
    }

    #sourcePage .sources-menu-container {
        overflow-x: scroll;
        padding-bottom: 20px;
    }

    #sourcePage .source-menu-links {
        color: white;
        cursor: pointer;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        width: 7em;
        padding: 15px;
        height: fit-content;
        flex-flow: column wrap;
    }

    #sourcePage .source-menu-links:hover {
        background-color: var(--primary-color);
        border-radius: 5px;
    }

    #sourcePage .source-menu-links.active i, .source-menu-links.active span {
        /*font-size: 2.5em;*/
        /*color: rgb(248, 193, 69);*/
        color: var(--decisions-color);
        font-weight: 600;
    }

    #sourcePage .source-menu-links i {
        font-size: 2em;
        padding-bottom: 5px;
    }

    #sourcePage .collapsible-header button {
        height: 1em;
    }

    #sourcePage .collapsible-header button:focus, .collapsible-header button:active {
        color: inherit !important;
    }

    #sourcePage .collapsible-header button:hover {
        transform: none;
    }

    #sourcePage .collapsible-header button::after {
        margin-left: 0.5em !important;
        font-size: 0.75em;
    }

    #sourcePage table .code {
        color: #ff8181;
        background-color: #262626;
    }

    #sourcePage table tr th {
        font-weight: 400;
        font-size: 0.75rem;
        color: gray;
    }

    #sourcePage table tbody tr:hover, table tbody tr.selected {
        background-color: rgba(255, 255, 255, 0.1) !important;
    }

    #sourcePage table input.fact-score {
        width: 5em;
    }

    #sourcePage table .index-column {
        color: var(--dark-gray);
    }

    #sourcePage .toggle-on.toggleSlider.toggleSlider::before {
        transform: translatex(24px);
    }

    #sourcePage .toggleSwitch {
        width: 55px;
        height: 28px;
    }

    #sourcePage .toggle-off {
        background-color: var(--primary-color);
    }

    #sourcePage .toggleSlider::before {
        position: absolute;
        content: "";
        height: 20px;
        width: 20px;
        bottom: 4px;
        transition: all 0.3s ease;
        left: 3px;
        top: 2px;
    }

    /*IMPORTED*/
    #sourcePage td.origin-IMPORTED {
        color: #848484;
    }

    /*SEEDED*/
    #sourcePage td.origin-SEEDED {
        color: #4a9;
    }

    /*LEARNED*/
    #sourcePage td.origin-LEARNED {
        color: #ffc500;
    }

    /*USER*/
    #sourcePage td.origin-USER {
        color: #a05195;
    }

    /*DOMAIN*/
    #sourcePage td.origin-DOMAIN {
        color: cornflowerblue;
    }

</style>
